import {
	API_URL,
	IM_API_URL
} from '@/common/common.js';
export function request(params) {
	return new Promise((resolve, reject) => {
		const token = uni.getStorageSync('token');
		uni.request({
			url: API_URL + '/' + params.url,
			method: params.method,
			data: params.data,
			header: {
				'Authorization': token,
				'content-type': 'application/json'
			},
			success: (res) => {
				if (res.statusCode === 200 || res.statusCode === 201) {
					resolve(res.data);
				} else {
					reject(res);
				}
			},
			fail: (err) => {
				reject(err);
			}
		});
	});
}

export function imRequest(params) {
	return new Promise((resolve, reject) => {
		const token = uni.getStorageSync('token');
		uni.request({
			url: IM_API_URL + '/' + params.url,
			method: params.method,
			data: params.data,
			header: {
				'Authorization': token,
				'content-type': 'application/json'
			},
			success: (res) => {
				if (res.statusCode === 200) {
					resolve(res.data);
				} else {
					reject(res);
				}
			},
			fail: (err) => {
				reject(err);
			}
		});
	});
}

export function upload(tempFilePath) {
	return new Promise((resolve, reject) => {
		const token = uni.getStorageSync('token');
		console.log("tempFilePath", tempFilePath)
		uni.uploadFile({
			url: API_URL + '/file/upload', // 你的上传接口地址
			filePath: tempFilePath,
			name: 'file',
			formData: {
				'user': 'test'
			},
			success: (uploadRes) => {
				console.log(uploadRes.data); // 打印服务器返回的数据
				resolve(uploadRes.data);
			},
			fail: (err) => {
				reject(err);
			}
		});
	});
}

export function batchUpload(paths) {
	const token = uni.getStorageSync('token');
	const uploadPromises = paths.map((item) => {
		console.log(item); 
		return new Promise((resolve, reject) => {
			uni.uploadFile({
				url: API_URL + '/file/upload', // 你的上传接口地址
				filePath: item,
				name: 'file',
				success: (uploadRes) => {
					console.log(uploadRes.data); // 打印服务器返回的数据
					resolve(uploadRes.data.replace(/"/g, ""));
				},
				fail: (err) => {
					reject(err);
				}
			});
		});
	});
	// 使用 Promise.all 等待所有的上传操作完成
	return Promise.all(uploadPromises);
}


export function batchUploadPorductImg(paths) {
	const token = uni.getStorageSync('token');
	const uploadPromises = paths.map((item) => {
		console.log(item); 
		return new Promise((resolve, reject) => {
			uni.uploadFile({
				url: API_URL + '/file/upload/product/image', // 你的上传接口地址
				filePath: item,
				name: 'file',
				success: (uploadRes) => {
					console.log(uploadRes.data); // 打印服务器返回的数据
					resolve(uploadRes.data.replace(/"/g, ""));
				},
				fail: (err) => {
					reject(err);
				}
			});
		});
	});
	// 使用 Promise.all 等待所有的上传操作完成
	return Promise.all(uploadPromises);
}